package com.kstech.ks_gaz01.fragments

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.ToggleButton
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankii.androidlibrary.utils.CalcUtil
import com.blankii.androidlibrary.views.DividerItemDecoration
import com.google.android.material.snackbar.Snackbar
import com.kstech.ks_gaz01.R
import com.kstech.ks_gaz01.XML_ADDRESS_SIMULATION_CHOOSE
import com.kstech.ks_gaz01.XML_ADDRESS_SIMULATION_DATAHEAD
import com.kstech.ks_gaz01.XML_ADDRESS_SIMULATION_HEART
import com.kstech.ks_gaz01.XML_ADDRESS_SIMULATION_OPEN
import com.kstech.ks_gaz01.XML_SIMULATION
import com.kstech.ks_gaz01.data.DebugDataBean
import com.kstech.ks_gaz01.data.DebugDataBean.zt_array
import com.kstech.ks_gaz01.databinding.FragmentSimulationBinding
import com.kstech.ks_gaz01.databinding.LayoutDialogZtBinding
import com.kstech.ks_gaz01.realTime.ChildFragment
import com.kstech.ks_gaz01.realTime.DialogAdapter
import com.kstech.ks_gaz01.realTime.SimulationAdapter
import com.kstech.ks_gaz01.socket.SocketManagerNew
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * author: blankii
 * created on: 2024/5/8 11:14
 * description: 仿真界面
 */
class SimulationFragment : ChildFragment(), View.OnClickListener, View.OnTouchListener {

    private var _binding: FragmentSimulationBinding? = null

    // 只能在onCreateView与onDestroyView之间的生命周期里使用
    private val binding: FragmentSimulationBinding get() = _binding!!
    private val simulationList = ArrayList<DebugDataBean.Item>()
    private lateinit var simulationAdapter: SimulationAdapter

    //    private val simulationCheckBox = booleanArrayOf(false, false, false, false, false, false, false)
//    private lateinit var _9001_Parent: DebugDataBean.Parent
//    private lateinit var _9001_Address: String

    //    private lateinit var _9002_Parent: DebugDataBean.Parent
//    private lateinit var _9002_Address: String
//    private lateinit var _9003_Parent: DebugDataBean.Parent
//    private lateinit var _9003_Address: String
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        _binding = FragmentSimulationBinding.inflate(inflater, container, false)
        return binding.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()


        /**
         * 请求仿真三个实时参数
         */
//        _9002_Parent = DebugDataBean.xmlMap[XML_SIMULATION]!![1]
//        _9002_Address =
//            (_9002_Parent.itemList[0].para0.toInt() - 1).toString()
//        val revData2 =
//            _9002_Parent.itemList[0].para2
        /**
         * 模拟操作
         */
//        _9003_Parent = DebugDataBean.xmlMap[XML_SIMULATION]!![2]
//        _9003_Address =
//            (_9003_Parent.itemList[0].para0.toInt() - 1).toString()
//        val revData3 =
//            _9003_Parent.itemList[0].para2

        initHeart()
    }


    private var clickSimulationPosition = -1
    private fun initView() {
        binding.apply {
            /**
             * 初始化操作信号recyclerView
             */
            recyclerView.layoutManager = GridLayoutManager(requireActivity(), 2)
            simulationAdapter = SimulationAdapter()
            recyclerView.adapter = simulationAdapter
            simulationList.addAll(DebugDataBean.xmlMap[XML_SIMULATION]!![0].itemList)
            simulationAdapter.submitList(simulationList)
            simulationAdapter.notifyDataSetChanged()
            /**
             * 绑定childClickListener
             */
            simulationAdapter.setOnItemClickListener { adapter, view, position ->
                val currentState = simulationList[position].isCheckBox
                simulationList[position].isCheckBox = !currentState
                simulationAdapter.notifyItemChanged(position)
                sendCheckBoxState()
            }
//            simulationAdapter.addOnItemChildClickListener(R.id.checkBox) { adapter, view, position ->
//                val currentState = simulationList[position].isCheckBox
//                simulationList[position].isCheckBox = !currentState
//                simulationAdapter.notifyItemChanged(position)
//                sendCheckBoxState()
//            }
            // 需要传递控件 id
            simulationAdapter.addOnItemChildClickListener(R.id.value) { adapter, view, position ->
//                globalPrintln("value:$position")
                showAlertDialog(position)
                clickSimulationPosition = position
            }
            /**
             * setOnClickListener
             * 绑定模拟操作点击事件
             */
            openFangZhen.setOnClickListener(this@SimulationFragment)
//            button1.setOnClickListener(this@SimulationFragment)
//            button2.setOnClickListener(this@SimulationFragment)
//            button9.setOnClickListener(this@SimulationFragment)

            /**
             * setOnTouchListener
             * 绑定模拟操作点击事件
             */
//            button3.setOnTouchListener(this@SimulationFragment)
//            button4.setOnTouchListener(this@SimulationFragment)
//            button5.setOnTouchListener(this@SimulationFragment)
//            button6.setOnTouchListener(this@SimulationFragment)
//            button7.setOnTouchListener(this@SimulationFragment)
//            button8.setOnTouchListener(this@SimulationFragment)
        }
    }

    private fun sendCheckBoxState() {
        var result = ""

        simulationList.forEach {
            result += if (it.isCheckBox) {
                "1"
            } else {
                "0"
            }
        }
        result += "000000000000"
        val intStr = Integer.valueOf(result, 2).toString()
        SocketManagerNew.sendWriteMsg(
            XML_ADDRESS_SIMULATION_CHOOSE,
            intStr,
        )
        Log.e("通讯", "44361-checkbox:${intStr}")
    }

    /**
     * 显示输入对话框
     */
    private fun showAlertDialog(position: Int) {
        val dialogBinding = LayoutDialogZtBinding.inflate(layoutInflater)
        val currentItem = simulationList[position]
        dialogBinding.dialogRecyclerView.layoutManager = LinearLayoutManager(requireActivity())
        dialogBinding.dialogRecyclerView.addItemDecoration(
            DividerItemDecoration(
                requireActivity(), R.color.background_logoBar
            )
        )
        val adapter = DialogAdapter()
        adapter.submitList(zt_array)
        dialogBinding.dialogRecyclerView.adapter = adapter
//        if (position <= 3) {
//            dialogBinding.editTextNumber.keyListener = DigitsKeyListener.getInstance("1234")
//            dialogBinding.editTextNumber.filters = arrayOf(InputFilter.LengthFilter(1))
//        } else {
//            dialogBinding.editTextNumber.keyListener = DigitsKeyListener.getInstance("0123456789-")
//        }
        val dialogBuilder = AlertDialog.Builder(requireActivity()).setView(dialogBinding.root)
            .setTitle("${currentItem.para1}").setMessage("请选择")
//        dialogBinding.editTextNumber.requestFocus()
        val dialog = dialogBuilder.show()
        adapter.setOnItemClickListener { adapter, view, position ->
            currentItem.revData = (position + 1).toString()
            simulationAdapter.notifyDataSetChanged()
            sendData(currentItem)
            dialog.dismiss()
        }
    }

    private fun sendData(currentItem: DebugDataBean.Item) {
        SocketManagerNew.sendWriteMsg(
            currentItem.para0, currentItem.revData, currentItem.isNegativeNumber
        )
    }

    /**
     * address 发送写入
     * isPositiveNum true=发送1 false=发送0
     */
    private fun sendButtonData(address: String, isPositiveNum: Boolean) {
        if (isPositiveNum) {
            SocketManagerNew.sendWriteMsg(
                address, "1"
            )
        } else {
            SocketManagerNew.sendWriteMsg(
                address, "0"
            )
        }

    }

    private fun showSnackBar(text: String) {
        Snackbar.make(requireActivity(), binding.root, text, 1200).show()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
        simulationWork = false
    }

    override fun writeSuccess(address: String, value: String) {

    }

    override fun readSuccess(address: String, result: ArrayList<String>) {
        when (address) {
//            _9002_Address -> {
//                binding.workHeight.text = CalcUtil.Hex2IntStr(result[0], true)
//                binding.workRadius.text = CalcUtil.Hex2IntStr(result[1])
//                binding.ruleRadius.text = CalcUtil.Hex2IntStr(result[2])
//            }
            XML_ADDRESS_SIMULATION_DATAHEAD -> {//模拟信号-模拟信号-数据组头
                if (simulationList.size == result.size && clickSimulationPosition < result.size && clickSimulationPosition >= 0) {
                    simulationList[clickSimulationPosition].revData = CalcUtil.Hex2IntStr(
                        result[clickSimulationPosition],
                        simulationList[clickSimulationPosition].isNegativeNumber
                    )
                    simulationAdapter.notifyItemChanged(clickSimulationPosition)
                }
            }
//            _9003_Address -> {
//                binding.button1.isChecked = CalcUtil.Hex2IntStr(result[0]) == "1"
//                binding.button2.isChecked = CalcUtil.Hex2IntStr(result[1]) == "1"
//                binding.button9.isChecked = CalcUtil.Hex2IntStr(result[8]) == "1"
//            }
            XML_ADDRESS_SIMULATION_OPEN -> {
                binding.openFangZhen.isChecked = result[0] == "00FA"
            }
        }
    }

    override fun pageOnResume() {
        /**
         * 模拟信号
         */
        val _9001_Parent = DebugDataBean.xmlMap[XML_SIMULATION]!![0]
        val _9001_Address = (_9001_Parent.itemList[0].para0.toInt() - 1).toString()
        val revData1 = _9001_Parent.itemList[0].para2
        RealTimePartFragment.addReadyList(
            true, arrayListOf(
                SocketManagerNew.ReadBean(
                    _9001_Address, revData1, _9001_Parent.itemList.size
                ),
//                SocketManagerNew.ReadBean(
//                    _9002_Address,
//                    revData2,
//                    _9002_Parent.itemList.size
//                ),
//                SocketManagerNew.ReadBean(
//                    _9003_Address,
//                    revData3,
//                    _9003_Parent.itemList.size
//                )
                SocketManagerNew.ReadBean(
                    XML_ADDRESS_SIMULATION_OPEN
                )
            )
        )
    }

    override fun pageOnPause() {
        super.pageOnPause()
        /**
         *  如果没有关闭仿真就退出，自动发送
         */
        sendButtonData(XML_ADDRESS_SIMULATION_OPEN, false)
        heartTag = false
        Log.e("ug", "Simulation-onPause")
    }

    override fun onClick(p0: View?) {
        when (p0!!.id) {
//            /**
//             * 油门中速
//             */
//            R.id.button1 -> {
//                if ((p0 as ToggleButton).isChecked) {
//                    sendButtonData("44375", true)
//                } else {
//                    sendButtonData("44375", false)
//                }
//            }
//            /**
//             * 油门高速
//             */
//            R.id.button2 -> {
//                if ((p0 as ToggleButton).isChecked) {
//                    sendButtonData("44376", true)
//                } else {
//                    sendButtonData("44376", false)
//                }
//            }
//            /**
//             * 规则解除
//             */
//            R.id.button9 -> {
//                if ((p0 as ToggleButton).isChecked) {
//                    sendButtonData("44383", true)
//                } else {
//                    sendButtonData("44383", false)
//                }
//            }
            /**
             * 打开仿真
             */
            R.id.openFangZhen -> {
                if ((p0 as ToggleButton).isChecked) {
                    SocketManagerNew.sendWriteMsg(
                        XML_ADDRESS_SIMULATION_OPEN, "250"
                    )
                    heartTag = true
                } else {
                    sendButtonData(XML_ADDRESS_SIMULATION_OPEN, false)
                    heartTag = false
                }
            }
        }
    }

    /**
     * 心跳机制
     * 在仿真状态下，1秒内至少自动写一次，数值0~65535累加，循环
     */
    private var heartCount = 0
    private var heartTag = false
    private var simulationWork = true
    private fun initHeart() {
        CoroutineScope(Dispatchers.IO).launch {
            while (simulationWork) {
                if (!heartTag) {
                    continue
                }
                SocketManagerNew.sendWriteMsg(
                    XML_ADDRESS_SIMULATION_HEART, heartCount.toString()
                )
                heartCount++
                if (heartCount > 65535) {
                    heartCount = 0
                }
                delay(500)
            }
        }
    }

    override fun onTouch(p0: View?, p1: MotionEvent?): Boolean {
        when (p0!!.id) {
            /**
             * 起伏上
             */
//            R.id.button3 -> {
//                when (p1!!.action) {
//                    MotionEvent.ACTION_DOWN -> {
//                        sendButtonData("44377", true)
//                    }
//                    MotionEvent.ACTION_UP -> {
//                        sendButtonData("44377", false)
//                    }
//                }
//            }
//            /**
//             * 起伏下
//             */
//            R.id.button4 -> {
//                when (p1!!.action) {
//                    MotionEvent.ACTION_DOWN -> {
//                        sendButtonData("44378", true)
//                    }
//                    MotionEvent.ACTION_UP -> {
//                        sendButtonData("44378", false)
//                    }
//                }
//            }
//            /**
//             * 伸缩伸
//             */
//            R.id.button5 -> {
//                when (p1!!.action) {
//                    MotionEvent.ACTION_DOWN -> {
//                        sendButtonData("44379", true)
//                    }
//                    MotionEvent.ACTION_UP -> {
//                        sendButtonData("44379", false)
//                    }
//                }
//            }
//            /**
//             * 伸缩缩
//             */
//            R.id.button6 -> {
//                when (p1!!.action) {
//                    MotionEvent.ACTION_DOWN -> {
//                        sendButtonData("44380", true)
//                    }
//                    MotionEvent.ACTION_UP -> {
//                        sendButtonData("44380", false)
//                    }
//                }
//            }
//            /**
//             * 回转顺
//             */
//            R.id.button7 -> {
//                when (p1!!.action) {
//                    MotionEvent.ACTION_DOWN -> {
//                        sendButtonData("44381", true)
//                    }
//                    MotionEvent.ACTION_UP -> {
//                        sendButtonData("44381", false)
//                    }
//                }
//            }
//            /**
//             * 回转逆
//             */
//            R.id.button8 -> {
//                when (p1!!.action) {
//                    MotionEvent.ACTION_DOWN -> {
//                        sendButtonData("44382", true)
//                    }
//                    MotionEvent.ACTION_UP -> {
//                        sendButtonData("44382", false)
//                    }
//                }
//            }
        }
        return false
    }
}